const Router = require('koa-router');
const {db, Op, DataTypes} = require("../models/db");
const tool = require("../tools/tool");
const router = new Router();
// 登录
router.post('/goods/save', async ctx => {
    try {
        let tid = ctx.user.tenantId;
        let uid = ctx.user.id;
        let formData = ctx.request.body.formData;
        let where = {
            tenantId: tid,
            name: formData.name
        }
        if(formData.id) {
            where.id = {
                [Op.ne]: formData.id
            }
            formData.uby = uid
            formData.utime = tool.getTime()
        }
        let c = await db.models['goods'].count({
            where
        })
        if(c > 0) return ctx.err('已存在相同的商品名称')

        if(formData.unit1 === formData.unit2) {
            if(formData.spec != 1) return ctx.err('大单位不能等于小单位')
        }
        if(formData.spec < 1) return ctx.err('规格请输入整数')

        if(formData.id) {
            let model = await db.models['goods'].findOne({
                where: {
                    tenantId: tid,
                    id: formData.id
                }
            })
            if(!model) return ctx.err('查询商品失败')
            let used = await db.models['invoiceInfo'].count({
                where: {
                    invId: formData.id
                }
            })
            let d = await db.models['inventoryDetail'].count({
                where: {
                    invId: formData.id,
                    transTypeName: {
                        [Op.ne]: '期初'
                    }
                }
            })
            if(used > 0 || d > 0) {
                if(model.spec != formData.spec) {
                    return ctx.err('已使用商品，不能再修改规格')
                }
                if(model.unit1) {
                    if(model.unit1 != formData.unit1) {
                        return ctx.err('已使用商品，不能再修改大单位')
                    }
                }
                else {
                    if(formData.unit1) return ctx.err('已使用商品，不能再修改大单位')
                }
                if(model.unit2) {
                    if(model.unit2 != formData.unit2) {
                        return ctx.err('已使用商品，不能再修改小单位')
                    }
                }
                else {
                    if(formData.unit2)  return ctx.err('已使用商品，不能再修改小单位')
                }
                if(formData.price1 != model.price1) {
                    return ctx.err('已使用商品，不能修改大单位成本')
                }
            }
            formData.uby = uid
            formData.utime = tool.getTime()
               formData.lowQty = tool.xe.toNumber(formData.lowQty)
            formData.highQty = tool.xe.toNumber(formData.highQty)
            formData.price1 = formData.price1?tool.xe.toNumber(formData.price1):0
            formData.price2 = formData.price2?tool.xe.toNumber(formData.price2):0

            await db.transaction(async t => {
                await db.models['goods'].update(formData, {
                    where: {
                        id: formData.id,
                    }
                },{transaction: t})
                let good = formData
                good.tenantId = tid
            })
            return ctx.suc('已更新')
        }
        else {
               formData.lowQty = tool.xe.toNumber(formData.lowQty)
            formData.highQty = tool.xe.toNumber(formData.highQty)
            formData.price1 = formData.price1?tool.xe.toNumber(formData.price1):0
            formData.price2 = formData.price2?tool.xe.toNumber(formData.price2):0

            formData.tenantId = tid
            formData.cby = uid
            formData.ctime = tool.getTime()
            formData.isDel = 0
            await db.transaction(async t => {
                await db.models['goods'].create(formData, {transaction: t})
            })
            return ctx.suc('已保存')
        }
    }
    catch (error) {
        console.log('商品保存失败',error)
        ctx.err(error)
    }
})
// 库存余额表写期初数
const setInventory = async (good, t) => {
    let storage = await db.models['storage'].findAll({
        where: {
            tenantId: good.tenantId
        }
    })
    for (let i = 0; i < storage.length; i++) {
        let lid = storage[i].id
        let c = await db.models['inventoryDetail'].findOne({
            where: {
                tenantId: good.tenantId,
                locationId: lid,
                invId: good.id,
                transTypeName: '期初'
            }
        })
        let hasMain = await db.models['inventory'].findOne({
            where: {
                tenantId: good.tenantId,
                locationId: lid,
                invId: good.id
            }
        })
        if(!c) {
            let detail = db.models['inventoryDetail'].build()
            detail.tenantId = good.tenantId
            detail.locationId = lid
            detail.invId = good.id
            detail.billNo = ''
            detail.relId = 0
            detail.transType = 0
            detail.balanceCount = 0
            detail.balancePrice = good.price1?(tool.Np.divide(good.price1, good.spec)):0
            detail.balanceMoney = 0
            detail.transTypeName = '期初'
            detail.billDate = '1970-01-01'
            detail.unit = good.unit2 ? good.unit2:good.unit1
            detail.unit1 = good.unit1
            detail.unit2 = good.unit2
            detail.spec = good.spec
            detail.calNum = 1
            detail.isCal = 1
            detail.seq = 1
            detail.ctime = tool.getTime()
            detail.utime = tool.getTime()
            await detail.save({transaction: t})
        }
        if(c) {
            if(!c.balanceCount) {
                c.balancePrice = good.price1?(tool.Np.divide(good.price1, good.spec)):0
                await c.save({transaction: t})
            }
        }
        if(!hasMain) {
            let detail = db.models['inventory'].build()
            detail.tenantId = good.tenantId
            detail.locationId = lid
            detail.invId = good.id
            await detail.save({transaction: t})
        }
    }
}
// 删除商品
router.post('/goods/delById', async ctx => {
    let ids = ctx.request.body.ids
    let c = await db.models['invoiceInfo'].count({
        where: {
            invId: {
                [Op.in]: ids
            }
        }
    })
    if(c > 0) {
        return  ctx.err('商品已使用,不能删除')
    }
    c = await db.models['initGoods'].count({
        where: {
            invId: {
                [Op.in]: ids
            }
        }
    })
    if(c > 0) {
        return  ctx.err('商品已使用,不能删除')
    }
    await db.models['goods'].destroy({
        where: {
            id: {
                [Op.in]: ids
            }
        }
    })
    return ctx.suc('已删除')
})


router.post('/goods/addSend', async ctx => {
    try {
        let tenantId = ctx.user.tenantId;
        let uid = ctx.user.id;
        let ctime = date_format(now());
        let invId = body.invId ? body.invId : 0;
        let buId = body.buId ? body.buId : 0;
        let sendInvId = body.sendInvId ? body.sendInvId : 0;
        let buyQty = body.buyQty ? body.buyQty : 0;
        let sendQty = body.sendQty ? body.sendQty : 0;
        let calType = '按比例送';
        if (!buyQty) {
            return ctx.err('请输入买数量')
        }
        if (!sendQty) {
            return ctx.err('请输入赠数量')
        }

    } catch (error) {
        console.log(error)
        ctx.err(error)
    }
})
router.post('/goods/jpList', async ctx => {
    let tid = ctx.user.tenantId
    let sql = `
        select * from goods_jp where tenantId=${tid} and dt is null
    `
    let ret = await tool.page(ctx, sql)
    return ret
})
// 保存期初
router.post('/goods/saveInit', async ctx => {
    let user = ctx.user
    let body = ctx.request.body
    let tenantId = user.tenantId;
    let uid = user.id;
    let ctime = tool.getTime();
    let formData = body.formData
    let id = formData.id
    let start = await db.models['zqStart'].findOne({
        where: {
            tenantId: tenantId
        }
    })
    if (start) {
        return ctx.err('账套已启用, 不能再设置期初');
    }
    let invId = formData.invId ? formData.invId : 0;
    let good = await db.models['goods'].findOne({
        where: {
            tenantId: tenantId,
            id: invId
        }
    })
    if(!good) return ctx.err('未发现对应商品')

    let invName = good.name
    let locationId = formData.locationId ? formData.locationId : 0;
    let location = await db.models['storage'].findOne({
        where: {
            tenantId: tenantId,
            id: locationId
        }
    })
    if(!location) return ctx.err("仓库设置失败")
    let locationName = location.name
    let qty = formData.qty ? formData.qty : 0;
    let amount = formData.amount ? formData.amount : 0;
    let unit = formData.unit ? formData.unit : '';
    if (!unit) {
        return ctx.err('请输入单位');
    }
    if (!invId) {
        return ctx.err('请选择商品');
    }
    if (!locationId) {
        return ctx.err('请选择仓库');
    }
    if (!amount) {
        return ctx.err('请输入金额');
    }
    if (!qty) {
        return ctx.err('请输入数量');
    }
    if (unit != good.unit1 && unit != good.unit2 ) {
        return ctx.err(unit + ' 不是商品' + good.name +'的单位')
    }
    let saveData = {
        tenantId,
        locationId,
        locationName,
        invId,
        invName,
        unit,
        qty,
        amount
    }
    if (id) {

        saveData.uby = uid;
        saveData.utime = ctime;
        saveData.id = id;
        // 如果已有
        let hasone = await db.models['initGoods'].count({
            where: {
                tenantId,
                locationId,
                invId,
                id: {
                    [Op.ne]: id
                }
            }
        })
        if (hasone > 0) {
            return ctx.err('已有当前商品');
        }
        await db.models['initGoods'].update(saveData, {
            where: {
                id: id
            }
        })
    } else {
        saveData.cby = uid;
        saveData.ctime = ctime;
        // 如果已有
        let hasone = await db.models['initGoods'].count({
            where: {
                tenantId,
                locationId,
                invId
            }
        })
        if (hasone > 0) {
            return ctx.err('已有当前商品');
        }
        await db.models['initGoods'].create(saveData)
    }
    return ctx.suc('保存成功')
})
// 删除期初
router.post('/goods/delInit', async ctx => {
    let ids = ctx.request.body.ids
    let start = await db.models['zqStart'].findOne({
        where: {
            tenantId: ctx.user.tenantId,
        }
    })
    if (start) {
        return ctx.err('账套已启用, 不能再删除期初');
    }
    await db.models['initGoods'].destroy({
        where: {
            tenantId: ctx.user.tenantId,
            id: {
                [Op.in]: ids
            }
        }
    })
    return ctx.suc('已删除')
})


module.exports = router;
